import React, { Component } from "react";
import { observer } from "mobx-react";
import {Icon} from 'weaver-mobile';
import { MapPage } from "weaver-mobile-page";
import has from "lodash/has";

const companyIconUrl = "/hrm/hrm_e9/images/sign/marker_company.png";
const selfIconUrl = "/hrm/hrm_e9/images/sign/marker_self.png";
const Normal = MapPage.Normal;
let map;
const plugins = [];

@observer
export default class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      height: window.document.documentElement.clientHeight - 138,
    };
  }

  componentDidUpdate(){
    this.props.store.locationLoaded && this.initMapData();
  }

  getLocationOrWifiInfo = key => {
    let entity = null;
    const { store: { toJS, locationAndWifiInfo } } = this.props;
    const info = toJS(locationAndWifiInfo);
    if (info != null) {
      const { locationInfo, wifiInfo } = info;
      if (locationInfo != null && key === "location") {
        return locationInfo;
      }
      if (wifiInfo != null && key === "wifi") return wifiInfo;
    }
    return entity;
  };

  mapEvents = {
    created: instance => this.setMapInstance(instance),
    zoomchange: () => this.hideCircle(),
  };

  createIcon = image =>
    new window.AMap.Icon({
      image,
      // 图标尺寸
      size: new window.AMap.Size(36, 36),
      // 图标所用图片大小
      imageSize: new window.AMap.Size(36, 36),
    });

  setMapInstance = instance => {
    if (instance.CLASS_NAME === "AMap.Map") {
      map = instance;
      this.initMapData();
    }
  };

  initMapData = () =>{
    this.addMarkers();
    this.findNearly();
  }

  clearAllMarker = () => {
    let overlays = map.getAllOverlays("marker");
    overlays.map(overlay => {
      const extData = overlay.getExtData();
      has(extData, "id") && map.remove(overlay);
    });
    overlays = map.getAllOverlays("circle");
    overlays.map(overlay => {
      const extData = overlay.getExtData();
      has(extData, "id") && map.remove(overlay);
    });
  };

  hideCircle = () => {
    const zoom = map.getZoom();
    let overlays = map.getAllOverlays("circle");
    overlays.map(overlay => {
      zoom <= 11 && overlay.hide();
      zoom > 11 && overlay.show();
    });
  };

  addMarkers = () => {
    this.clearAllMarker();
    const locationInfo = this.getLocationOrWifiInfo("location");
    if (locationInfo != null && locationInfo.locationcheck) {
      let arr = [];
      const { locationcheckscope, locations } = locationInfo;
      locations.map(location => {
        const circle = new window.AMap.Circle({
          center: new window.AMap.LngLat(location.longitude, location.latitude), // 圆心位置
          radius: location.checkscope || 500,//locationcheckscope, //半径
          strokeColor: "#55B1F9", //线颜色
          strokeOpacity: 1, //线透明度
          strokeWeight: 2, //线粗细度
          fillColor: "#55b1f9", //填充颜色
          fillOpacity: 0.2, //填充透明度,
          extData: {
            id: location.id,
          },
        });
        map.add(circle);

        const marker = new window.AMap.Marker({
          icon: this.createIcon(companyIconUrl),
          position: new window.AMap.LngLat(
            location.longitude,
            location.latitude
          ),
          offset: new window.AMap.Pixel(-17, -34),
          extData: {
            id: location.id,
          },
        });
        map.add(marker);
        arr.push(marker);
      });
      let marker;
      const {store: {currentPositionData, toJS}} = this.props;
      const positionData = toJS(currentPositionData);
      const position = has(positionData, 'position') ? positionData.position : positionData;
      if(has(position, 'longitude')){
        let lnglat = new window.AMap.LngLat(Number(position.longitude), Number(position.latitude));
        marker = new window.AMap.Marker({
          icon: this.createIcon(selfIconUrl),
          position: lnglat,
          extData: {
            id: -1000,
          },
          offset: new window.AMap.Pixel(-17, -34),
        });
        map.add(marker);
      }
    }
  };

  findNearly = () => {
    const {store:{findNearly}} = this.props;
    const rs = findNearly();
    if(rs != null){
      const {positionObj: {nearlyLocation, dis}} = rs;
      const overlaysList = map.getAllOverlays('marker');
      let arr = [];
      overlaysList.map(overlay => {
        const extData = overlay.getExtData();
        if(has(extData, "id") && (extData.id == nearlyLocation.id || extData.id == -1000)){
          arr.push(overlay);
        }
      });
      setTimeout(() => {
        this.setFitView(arr);
      }, 100)
    }
  }

  setFitView = (overlaysList) => {
    map.setFitView(overlaysList);
  }

  getCurrLocation = () => {
    this.clearAllMarker();
    const {store: {relocate}} = this.props;
    relocate(this.initMapData);
  }

  render() {
    const { store } = this.props;
    const {outButtonsInfo: {isOutside, outsidesign}} = store;
    let height = this.state.height;
    if (isOutside && outsidesign == '1') 
    height -= 48;
    return (
      <div className="map" style={{ height }}>
        <Normal
          plugins={plugins}
          events={this.mapEvents}
          showIntroduction={false}
        >
          <div className='relocate' onClick={this.getCurrLocation}>
            <Icon className='icon' type='positioning' color='#999' size='ms'/>
          </div>
        </Normal>
      </div>
    );
  }
}
